import 'whatwg-fetch'
import axios from 'axios'
import qs from 'qs'
import jsonp from 'jsonp'
import lodash from 'lodash'
import pathToRegexp from 'path-to-regexp'
import { message } from 'antd'
import tokenHandler from 'utils/tokenHandler'

const mfetch = (options) => {
  let {
    method = 'get',
    data,
    fetchType,
    url,
  } = options
  let cloneData = null
  if (url.indexOf('files/upload') === -1) {
    cloneData = lodash.cloneDeep(data)
  } else {
    cloneData = data
  }
  try {
    let domin = ''
    if (url.match(/[a-zA-z]+:\/\/[^/]*/)) {
      domin = url.match(/[a-zA-z]+:\/\/[^/]*/)[0]
      url = url.slice(domin.length)
    }
    const match = pathToRegexp.parse(url)
    url = pathToRegexp.compile(url)(data)
    for (let item of match) {
      if (item instanceof Object && item.name in cloneData) {
        delete cloneData[item.name]
      }
    }
    url = domin + url
  } catch (e) {
    message.error(e.message)
  }

  if (fetchType === 'JSONP') {
    return new Promise((resolve, reject) => {
      jsonp(url, {
        param: `${qs.stringify(data)}&callback`,
        name: `jsonp_${new Date().getTime()}`,
        timeout: 4000,
      }, (error, result) => {
        if (error) {
          reject(error)
        }
        resolve({ statusText: 'OK', status: 200, data: result })
      })
    })
  } else if (fetchType === 'YQL') {
    url = `http://query.yahooapis.com/v1/public/yql?q=select * from json where url='${options.url}?${encodeURIComponent(qs.stringify(options.data))}'&format=json`
    data = null
  }
  let config = {}
  if (url.endsWith('/excel')) {
    config = {
      headers: {
        token: tokenHandler.getSessionByKey('token'),
      },
      responseType: 'blob',
    }
  } else if (url.indexOf('getcaptcha') !== -1) {
    config = {
      headers: {
        Accept: 'image/png',
      },
      responseType: 'arraybuffer',
    }
  } else if (url.indexOf('files/upload') !== -1) {
    config = {
      headers: {
        token: tokenHandler.getSessionByKey('token'),
        'Content-Type': 'multipart/form-data',
      },
      responseType: 'json',
    }
  } else if (url.indexOf('getimg') !== -1) {
    config = {
      headers: {
        token: tokenHandler.getSessionByKey('token'),
        Accept: 'image/png',
      },
      responseType: 'arraybuffer',
    }
  } else {
    config = {
      headers: {
        token: tokenHandler.getSessionByKey('token'),
        'Content-Type': 'application/json',
        Accept: 'application/json',
      },
      responseType: 'json',
    }
  }

  // 允许跨域携带身份信息
  axios.defaults.withCredentials = true
  // if(url.indexOf('login') !== -1){
  //   console.log('login');
  //   axios.defaults.withCredentials = true;
  // }

  switch (method.toLowerCase()) {
    case 'get':
      return axios.get(url, { params: cloneData, ...config })
    case 'delete':
      return axios.delete(url, {
        data: cloneData,
        ...config,
      })
    case 'post':
      return axios.post(url, cloneData, config)
    case 'put':
      return axios.put(url, JSON.stringify({ ...cloneData }), config)
    case 'patch':
      return axios.patch(url, cloneData, config)
    default:
      return axios({ ...options, ...config })
  }
}

export default function request (options) {
  // if (options.url && options.url.indexOf('//') > -1) {
  //   const origin = `${options.url.split('//')[0]}//${options.url.split('//')[1].split('/')[0]}`
  //   if (window.location.origin !== origin) {
  //     if (CORS && CORS.indexOf(origin) > -1) {
  //       options.fetchType = 'CORS'
  //     } else if (YQL && YQL.indexOf(origin) > -1) {
  //       options.fetchType = 'YQL'
  //     } else {
  //       options.fetchType = 'JSON'
  //     }
  //   }
  // }
  //

  return mfetch(options).then((response) => {
    const { statusText, status } = response
    let data = options.fetchType === 'YQL' ? response.data.query.results.json : response.data
    if (data instanceof Array) {
      data = {
        list: data,
      }
    }
    if (options.url.indexOf('getcaptcha') !== -1) {
      const base64Str = btoa(new Uint8Array(response.data).reduce((datas, byte) => datas + String.fromCharCode(byte), ''))
      return Promise.resolve(
        `data:image/png;base64,${base64Str}`
      )
    } else if (options.url.indexOf('getimg') !== -1) {
      const base64Str = btoa(new Uint8Array(response.data).reduce((datas, byte) => datas + String.fromCharCode(byte), ''))
      return Promise.resolve(
        `data:image/png;base64,${base64Str}`
      )
    } else if (options.url.endsWith('/excel')) {
      return Promise.resolve({
        success: true,
        message: statusText,
        statusCode: status,
        data,
      })
    }
    return Promise.resolve({
      success: true,
      message: statusText,
      statusCode: status,
      ...data,
    })
  }).catch((error) => {
    const { response } = error
    let msg
    let statusCode
    if (response && response instanceof Object) {
      const { data, statusText } = response
      statusCode = response.status
      msg = data.msg || statusText
    } else {
      statusCode = 600
      msg = error.msg || 'Network Error'
    }
    return Promise.reject({ success: false, statusCode, message: msg })
  })
}
